import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoCilent {
    private Socket socket = null;
    public TcpEchoCilent(String serverIP, int serverPort) throws IOException {
        socket = new Socket(serverIP, serverPort);
    }
    public void start() throws IOException {
        System.out.println("和服务连接成功~");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputStream = socket.getOutputStream()){
                while (true){
                    //1.从控制台读取字符串
                    System.out.print("->");
                    String request = scanner.next();
                    //2.根据读取的字符串，构造申请，把请求发送给服务器
                    PrintWriter printWriter = new PrintWriter(request);
                    printWriter.println(request);
                    printWriter.flush();
                    //3.从服务器中读取响应，并解析
                    Scanner respScanner = new Scanner(inputStream);
                    String response = respScanner.next();
                    //4.把结果显示到控制台上
                    System.out.printf("req: %s, resp: %s\n",request,response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoCilent cilent = new TcpEchoCilent("127.0.0.1",8080);
        cilent.start();
    }
}
